package com.zhangxin.aiInterview.manager.asr;

import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.vosk.Model;
import org.vosk.Recognizer;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 语音转文字公共服务
 */
//@Component
@Slf4j
@Deprecated
public class AudioManager {
    //项目启动时加载模型
//    @PostConstruct
    void initModel(){
        log.info("初始化模型");
        AudioToWordsModel.getInstance();
    }

    /**
     * 语音转文字
     * @param userId 用户id
     * @param path 用户音频文件路径
     * @throws IOException
     * @return 文字结果
     */
    public String videoToWords(Long userId,String path) throws IOException {
        // 1. 加载PCM音频文件
        FileInputStream pcmStream = new FileInputStream(path);
        // 2. 初始化Vosk
        try {
            Model model = AudioToWordsModel.getInstance();
            Recognizer recognizer = new Recognizer(model, 16000);
            byte[] buffer = new byte[8192];
            int bytesRead;
            long start = System.currentTimeMillis();
            // 3. 流式读取PCM并识别
            StringBuilder userContent = new StringBuilder();
            while ((bytesRead = pcmStream.read(buffer)) >= 0) {
                if (recognizer.acceptWaveForm(buffer, bytesRead)) {
                    String result = recognizer.getResult();
                    JSONObject jsonObject = new JSONObject(result);
                    String content = (String)jsonObject.get("text");
                    userContent.append(content);
                }
            }
            // 4.输出最终结果
            String result = recognizer.getResult();
            JSONObject jsonObject = new JSONObject(result);
            String content = (String)jsonObject.get("text");
            userContent.append(content);
            System.out.println("识别结果：" + userContent.toString().trim());
            System.out.println("识别总耗时：" + (System.currentTimeMillis() - start) + "ms");
            //返回语音识别结果
            return userContent.toString().trim();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            //清理资源
            pcmStream.close();
            deleteFile("temp_audio.webm");
            deleteFile("output.pcm");
        }
    }
    //删除文件
    public void deleteFile(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
    }
}